<template>
  <el-dropdown trigger="click" class="international" @command="handleSetLanguage">
    <div class="international-icon">
      <svg-icon icon-class="language" />
      <span class="language-text">{{ currentLanguageName }}</span>
    </div>
    <el-dropdown-menu slot="dropdown">
      <el-dropdown-item :disabled="language==='zh'" command="zh">
        <span role="img" aria-label="中文">🇨🇳</span> 中文
      </el-dropdown-item>
      <el-dropdown-item :disabled="language==='en'" command="en">
        <span role="img" aria-label="English">🇺🇸</span> English
      </el-dropdown-item>
      <el-dropdown-item :disabled="language==='th'" command="th">
        <span role="img" aria-label="ไทย">🇹🇭</span> ไทย
      </el-dropdown-item>
    </el-dropdown-menu>
  </el-dropdown>
</template>

<script>
import { setLanguage, getLanguage } from '@/utils/auth'

export default {
  name: 'LangSelect',
  computed: {
    language() {
      return this.$store.getters.language || getLanguage()
    },
    currentLanguageName() {
      const languageMap = {
        zh: '中文',
        en: 'English',
        th: 'ไทย'
      }
      return languageMap[this.language] || '中文'
    }
  },
  methods: {
    async handleSetLanguage(lang) {
      if (this.language === lang) {
        return
      }

      try {
        // 显示简单提示
        this.$message.info('切换语言中...')

        // 1. 更新 cookie
        setLanguage(lang)

        // 2. 更新 store
        await this.$store.dispatch('app/setLanguage', lang)

        // 3. 更新 i18n
        this.$i18n.locale = lang

        // 4. 加载 Element UI 语言包
        await this.loadElementUILocale(lang)

        // 5. 更新菜单
        await this.$store.dispatch('permission/updateMenuLanguage')

        // 显示成功消息
        this.$message.success('语言切换成功')

        // 刷新页面
        setTimeout(() => {
          window.location.reload()
        }, 500)

      } catch (error) {
        console.error('切换语言失败:', error)
        this.$message.error('语言切换失败')
      }
    },

    async loadElementUILocale(lang) {
      try {
        let locale
        switch (lang) {
          case 'en':
            locale = await import('element-ui/lib/locale/lang/en')
            break
          case 'th':
            locale = await import('element-ui/lib/locale/lang/th')
            break
          default:
            locale = await import('element-ui/lib/locale/lang/zh-CN')
        }
        this.$ELEMENT.locale(locale.default)
      } catch (error) {
        console.warn('加载 Element UI 语言包失败:', error)
      }
    }
  }
}
</script>
